package com.example.bletestutils.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.Timer;
import java.util.TimerTask;

public class MyTextView extends androidx.appcompat.widget.AppCompatTextView {
    private DownOrUpListener listener;

    private boolean isRunning = false;

    private Timer timer;
    public void setListener(DownOrUpListener listener) {
        this.listener = listener;
    }

    public MyTextView(@NonNull Context context) {
        this(context, null);
    }

    public MyTextView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyTextView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

//        init(context, attrs, defStyleAttr);
    }



    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (listener == null){
            return super.onTouchEvent(event);
        }
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            listener.onKeyDown(this);
            if (!isRunning) {
                isRunning = true;
                startTimer();
            }
        }
        //按钮松开，发送指令
        if (event.getAction()  == MotionEvent.ACTION_UP) {
            isRunning = false;
            timer.cancel();
            timer = null;
            listener.onKeyUp(this);
        }
//        return true;
        return super.onTouchEvent(event);
    }

    private void startTimer(){
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                listener.onKeyContinue(MyTextView.this);
            }
        },200,200);
    }
}
